from django.shortcuts import render
from django.http import HttpResponse
from django.http import JsonResponse
from sklearn import datasets
from sklearn.preprocessing import MinMaxScaler

from .backend import *
import json


def index(request):
    return render(request, "index.html", {"hello": "Hello world!"})

def newindex(request):
    return render(request, "newindex.html", {"hello": "Hello world!"})


def upload_file(request):
    if request.method == "POST":
        myFile = request.FILES.get("file", None)
        if not myFile:
            return HttpResponse("no file for upload")
        # destination = open(myFile.name,"wb+")
        # for chunk in myFile.chunks():
        #     destination.write(chunk)
        # destination.close()
        feature, data = readCSV("../hero_data.csv")
        # iris = datasets.load_wine()
        # data = iris.data
        # feature = iris.feature_names
        result_data = {
            "code": 1,
            "data": data.tolist(),
            "feature_names": feature,
        }
        return JsonResponse(result_data)

def cluster(request):
    feature,data = readData()
    feature = feature.tolist()
    transfer = MinMaxScaler(feature_range=[0, 1])
    # 调用fit_transform
    data_new = transfer.fit_transform(data)
    typelist = KMeans(n_clusters=4, random_state=9).fit_predict(data_new)
    # iris = datasets.load_iris()
    # data = iris.data
    # feature = iris.feature_names
    # data = np.array(data)
    # # typelist = kmeanscluster(num_val, data)
    # typelist = iris.target
    result = {}
    result["type"] = typelist.tolist()
    result["data"] = data.tolist()
    result["feature_names"] = feature
    return JsonResponse(result)

def showTSNE(request):
    if request.method == "POST":
       tmp = request.POST.get('showData')
       tmp = json.loads(tmp)
       n_feature = int(request.POST.get('n_feature'))
       dic = {}
       dic['data'] = showTSNEView(tmp,n_feature).tolist()
       return JsonResponse(dic)


def showPCA(request):
    if request.method == "POST":
       tmp = request.POST.get('showData')
       tmp = json.loads(tmp)
       n_feature = int(request.POST.get('n_feature'))
       dic = {}
       dic['data'] = showTSNEView(tmp,n_feature).tolist()
       return JsonResponse(dic)


def getRuleTree(request):
    if request.method == "POST":
        data = request.POST.get('data')
        data = json.loads(data)
        typeArray = request.POST.get('type')
        typeArray= json.loads(typeArray)
        featureImport = request.POST.get('featureImport')
        featureImport=json.loads(featureImport)
        treeInfo  = makeRuleTree(data, typeArray,featureImport)
        return JsonResponse(treeInfo)


def getFetureOrder(request):
    request_data = json.loads(request.body.decode("utf-8"))
    data= request_data['data']
    type = request_data['type']
    center = request_data['center']
    dic = getFeatureOrder(data,type,center)
    return JsonResponse(dic)

